package cn.iocoder.yudao.module.call.service.ivrflowbranchstat;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.call.dal.dataobject.ivrflow.IvrFlowBranchStatDO;
import cn.iocoder.yudao.module.call.dal.mysql.ivrflow.IvrFlowBranchStatMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import cn.iocoder.yudao.module.call.controller.admin.ivrflowbranchstat.vo.*;

import javax.annotation.Resource;
import java.util.*;

/**
 * ivr流程节点命中统计 Service 实现类
 *
 * @author 数创万维
 */
@Service
@Validated
@Slf4j
public class IvrFlowBranchStatServiceImpl implements IvrFlowBranchStatService {

    @Resource
    private IvrFlowBranchStatMapper ivrFlowBranchStatMapper;

    @Override
    public Long createIvrFlowBranchStat(IvrFlowBranchStatSaveReqVO createReqVO) {
        // 插入
        IvrFlowBranchStatDO ivrFlowBranchStat = BeanUtils.toBean(createReqVO, IvrFlowBranchStatDO.class);
        ivrFlowBranchStatMapper.insert(ivrFlowBranchStat);
        // 返回
        return ivrFlowBranchStat.getId();
    }

    @Override
    public void updateIvrFlowBranchStat(IvrFlowBranchStatSaveReqVO updateReqVO) {

        // 更新
        IvrFlowBranchStatDO updateObj = BeanUtils.toBean(updateReqVO, IvrFlowBranchStatDO.class);
        ivrFlowBranchStatMapper.updateById(updateObj);
    }

    @Override
    public void deleteIvrFlowBranchStat(Long id) {

        // 删除
        ivrFlowBranchStatMapper.deleteById(id);
    }


    @Override
    public IvrFlowBranchStatDO getIvrFlowBranchStat(Long id) {
        return ivrFlowBranchStatMapper.selectById(id);
    }

    @Override
    public PageResult<IvrFlowBranchStatDO> getIvrFlowBranchStatPage(IvrFlowBranchStatPageReqVO pageReqVO) {
        return ivrFlowBranchStatMapper.selectPage(pageReqVO);
    }


    /**
     * 更新节点命中率
     */
    @Override
    public void updateRatesByFlow(Long flowId, JSONObject stat) {
        if (ObjectUtil.isEmpty(stat)) {
            return;
        }
        log.info("stat_json:{}", stat);
        JSONObject nodeList = stat.getJSONObject("node");

        Set<String> nodeSet = nodeList.keySet();
        //挂断的节点
        String hangUpNode = stat.getStr("hangupNode");
        for (String nodeId : nodeSet) {
            JSONObject hitList = nodeList.getJSONObject(nodeId);
            Set<String> hitSet = hitList.keySet();
            log.info("hitList:{}", hitList);

            //先处理total 和 knowledge
            Long total = hitList.getLong("total");

            //这里total加上了历史总量
            total = updateRate(IvrFlowBranchStatDO.builder().flowId(flowId).nodeId(nodeId).amount(total).tag("total").build(), total).getAmount();
            //TODO: knowledge类型记录了knowledgeId,后期可统计每个知识库的命中量
            JSONArray knowledgeStat = hitList.getJSONArray("knowledge");
            updateRate(IvrFlowBranchStatDO.builder().flowId(flowId).nodeId(nodeId).amount((long) knowledgeStat.size()).tag("knowledge").build(), total);
            //挂断节点
            if (nodeId.equals(hangUpNode)) {
                updateRate(IvrFlowBranchStatDO.builder().flowId(flowId).nodeId(nodeId).amount((long) knowledgeStat.size()).tag("hangup").build(), total);
            }
            hitSet.remove("total");
            hitSet.remove("knowledge");
            log.info("hitSet:{}", hitSet);

            for (String hit : hitSet) {
                log.info("hit:{}", hit);
                log.info("amount:{}",hitList.getLong(hit));

                updateRate(IvrFlowBranchStatDO.builder().flowId(flowId).nodeId(nodeId).amount(hitList.getLong(hit)).tag(hit).build(), total);
            }
        }


    }

    /**
     * 单个更新
     */
    @Override
    public IvrFlowBranchStatDO updateRate(IvrFlowBranchStatDO updateDO, Long total) {
        IvrFlowBranchStatDO info = ivrFlowBranchStatMapper.selectOne(new LambdaQueryWrapperX<IvrFlowBranchStatDO>().eq(IvrFlowBranchStatDO::getFlowId, updateDO.getFlowId()).eq(IvrFlowBranchStatDO::getNodeId, updateDO.getNodeId()).eq(IvrFlowBranchStatDO::getTag, updateDO.getTag()));

        if (ObjectUtil.isNull(info)) {
            updateDO.setRate(NumberUtil.round(NumberUtil.div(updateDO.getAmount(), total).doubleValue() * 100, 2).doubleValue());
            ivrFlowBranchStatMapper.insert(updateDO);
        } else {
            updateDO.setId(info.getId());
            //修改时新增数量
            log.info("info: {} /n updateDo:{}", info, updateDO);
            updateDO.setAmount(info.getAmount() + updateDO.getAmount());
            if (!updateDO.getTag().equals("total")) {
                //total类型的不需要进行计算百分比
                updateDO.setRate(NumberUtil.round(NumberUtil.div(updateDO.getAmount(), total).doubleValue() * 100, 2).doubleValue());
            }
            ivrFlowBranchStatMapper.updateById(updateDO);
        }
        return updateDO;
    }


}